package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.pojo.entity.OrderSetting;
import com.itheima.health.pojo.result.Result;
import com.itheima.health.service.OrderSetService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ordersetting")
public class OrderSetController {

    @Autowired
    private OrderSetService orderSetService;

    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) {
        //接收前端上传来的excel文件并解析并提取数据
        List<OrderSetting> extractedData = new ArrayList<>();
        if (!excelFile.isEmpty()) {
            try (InputStream is = excelFile.getInputStream()) {
                Workbook workbook = new XSSFWorkbook(is);
                Sheet sheet = workbook.getSheetAt(0);

                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    Row row = sheet.getRow(rowNum);

                    if (row != null) {
                        // 假设日期和数量在第一列和第二列
                        int quantity = (int) row.getCell(1).getNumericCellValue();
                        Date date = row.getCell(0).getDateCellValue();

                        // 将提取的数据添加到列表中
                        extractedData.add(new OrderSetting(date, quantity));
                    }
                }
                System.out.println("aa");
                orderSetService.insertBatch(extractedData);
                // 这里可以根据需要返回解析结果或者状态信息
                return new Result(true, MessageConst.UPLOAD_SUCCESS);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(false, "上传失败");
            }
        } else {
            return new Result(false, "上传失败");
        }
    }

}
